defmodule SockWorkstation.Application do
  # See https://hexdocs.pm/elixir/Application.html
  # for more information on OTP Applications
  @moduledoc false

  use Application
  alias SockWorkstation.{CtrlMgrGen, SockCtrlClient,CoopTopSup,CoopHelperSup,SessionAgent,PingPongGen}
  # alias SockWorkstation.{PcmEncoderGen, OpusDecoderGen, OpusExileDeSev, OpusExileEnSev}
  # alias SockWorkstation.PythonRunnerGen
  @impl true
  def start(_type, _args) do
    children = [
      # Starts a worker by calling: SockWorkstation.Worker.start_link(arg)
      # {SockWorkstation.Worker, arg}
      {Registry, keys: :unique, name: SockWorkstation.SessionRegistry},
      {CoopTopSup, []},
      {CoopHelperSup, []},
      {SessionAgent, []},
      {CtrlMgrGen, []},
      {SockCtrlClient, []},
      {PingPongGen, []},
      # {SockWorkstation.NodeManagerGen, [:"mediaphx@72-j.cn"]}
      %{
        id: PanCouchbeamClient,
        start:
          {SockWorkstation.PanCouchbeamClient, :start_link,
           [
             %{
               options: [
                 basic_auth: Application.get_env(:couchbeam, :basic_auth),
                 timeout: 30_000
               ],
               url: "#{get_hostname()}:4005"
             }
           ]}
      },
      %{
        id: CollHelperGen,
        start: {SockWorkstation.CollHelperGen, :start_link, [[]]}
      }

      # {PythonRunnerGen, []},
      # {PcmEncoderGen, []},
      # {OpusExileDeSev, []},
      # {OpusExileEnSev, []}
      # {SockWorkstation.Mp3toPcmExile,[]},
      # {OpusDecoderGen, []},

      # {SockWorkstation.FFmpegPlayer, []},
      # %{
      #   id: FFmpegPlayer,
      #   start: {FFmpegPlayer, :start_link, []}
      # }
      # %{id: WSPort,start: {Port, [:binary, {:spawn_executable, "ffmpeg -f opus -i pipe:0 -f pulse default"}]}}
    ]

    # See https://hexdocs.pm/elixir/Supervisor.html
    # for other strategies and supported options
    opts = [strategy: :one_for_one, name: SockWorkstation.Supervisor]
    Supervisor.start_link(children, opts)
  end

  def get_hostname() do
    case :inet.gethostname() do
      {:ok, hostname} ->
        # hostname =
        if hostname == ~c"T2" do
          "db.72-j.cn"
        else
          "10.0.0.224"
        end

      # hostname

      # to_string(hostname)

      {:error, reason} ->
        IO.puts("Failed to get hostname: #{inspect(reason)}")
        nil
    end
  end

    def super_helper(session_id) do
    # 生成唯一的 ID
    unique_id = make_ref()

    spec = %{
      id: {:worker, unique_id},
      start: {SockWorkstation.CoopHelperSup, :start_link, [session_id]},
      restart: :temporary
    }

    DynamicSupervisor.start_child(__MODULE__, spec)
    # case DynamicSupervisor.start_child(__MODULE__, spec) do
    #   {:ok, pid} ->
    #     {:ok, pid}

    #   {:error, {:already_started, pid}} ->
    #     {:ok, pid}

    #   {:error, _} ->
    #     IO.puts("start super helper failed")
    # end
  end

  def shutdown_coophelper_gen do
    children = DynamicSupervisor.which_children(CoopHelperSup) |> Enum.reverse()

    # 先停止所有子进程
    Enum.each(children, fn {_, pid, _, _} ->
      GenServer.stop(pid, :normal, 2000)
    end)

  end

  # def stop(_state) do
  #   # 在这里执行清理操作
  #   IO.puts("Application is shutting down")
  # end
end
